package bro2Advanced.threads;

import java.util.concurrent.CountDownLatch;

/**
 * 锁分类和JUC
 *  CountDownLatch 的使用示例
 */
public class InitializationDemo {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);
        Thread service1 = new Thread(new Service("service 1", 2000, latch));
        Thread service2 = new Thread(new Service("service 2", 2000, latch));
        Thread service3 = new Thread(new Service("service 3", 2000, latch));

        service1.start();
        service2.start();
        service3.start();

        // 等待所有服务初始化完成
        latch.await();
        System.out.println("所有服务都准备好了");
    }

    static class Service implements Runnable {
        private final String name;
        private final int timeToStart;
        private final CountDownLatch latch;

        public Service(String name, int timeToStart, CountDownLatch latch) {
            this.name = name;
            this.timeToStart = timeToStart;
            this.latch = latch;
        }
        @Override
        public void run() {
            try {
                Thread.sleep(timeToStart);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println(name + " 准备好了");
            latch.countDown(); // 减少倒计数
        }


    }
}
